package com.hk.Mgr.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hk.Mgr.web.dto.FinancialLeaveDTO;
import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.sys.SysUserChangePwdReq;
import com.hk.Mgr.web.message.sys.SysUserReq;
import com.hk.Mgr.web.message.sys.SysUserRolesReq;
import com.hk.app.utils.ExcelService;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.*;
import com.hk.commons.enm.MicroServiceType;
import com.hk.commons.enm.OperationEvent;
import com.hk.commons.entity.AccountBalance;
import com.hk.commons.entity.LogUtil;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.sys.SysUserRoles;
import com.hk.commons.entity.sys.UserChangeInfo;
import com.hk.commons.entity.view.SysUserExcelView;
import com.hk.commons.entity.view.UserView;
import com.hk.commons.utils.IPUtil;
import com.hk.commons.utils.sys.DateHelper;
import com.hk.commons.utils.sys.MD5Crypter;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.CloseAccountReq;
import com.hk.commons.vo.OperationLogDTO;
import com.hk.commons.vo.SysUserExcelMsg;
import com.hk.commons.vo.app.SysUserMsg;
import com.hk.context.SysUserContext;
import com.hk.service.IOrganization;
import com.hk.service.IOrganization_New;
import com.hk.service.ISafety;
import com.hk.service.OperationLogService;
import com.hk.service.kyc.ICoupon;
import com.hk.service.kyc.ILogUtil;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.IPayment;
import com.hk.service.sys.*;
import com.hk.service.view.ISysUserExcelView;
import com.hk.service.view.IUserView;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lemon 用户实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/SysUserCtrl")
public class SysUserCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(SysUserCtrl.class);

	@Autowired
	private ISysUser sysUserService;


	@Autowired
	private IUserChangeInfo userChgService;

	@Autowired
	private IUserView userViesService;

	@Autowired
	private ISysUserRoles sysUserRolesService;
	 
	
	@Autowired
	private ICoupon couponService;

	@Autowired
	private ILogUtil logService;


	@Autowired
	private IOrganization orgService;

	@Autowired
	private IOrganization_New orgNewService;

	@Autowired
	private IPayment paymentService;

	@Autowired
	private ISafety safetyService;

	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private SysUserContext sysUserContext;

	@Autowired
	private ISysUserExcelView sysUserExcelService;

	@Autowired
	private OperationLogService operationLogService;

	// 请求clientId
	@Value("${sysuser.pwd.init}")
	private String initpwd;


	@Value("${pdf.address}")
	private String filePath;


	@ResponseBody
	@RequestMapping(value = "/getPaymentByUserId", method = RequestMethod.POST)
	public ResponseBase<Map<String, Object>> getPaymentByUserId(
			@RequestBody SysUserReq req) {
		ResponseBase<Map<String, Object>> resp = new ResponseBase<Map<String, Object>>();
		Long userId = req.getId();
		HqlFilter hqlFilter = new HqlFilter();
		List<Payment> paymentList = paymentService.findByFilter(hqlFilter);
		if (paymentList.size() > 0) {
			for (Payment p : paymentList) {
				String paymentNo = p.getPaymentNo();
				String identity = p.getIdentityNo();
			}
		}
		return resp;
	}

	/**
	 * 根据手机号获取用户id
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getIdByPhoneNum", method = RequestMethod.POST)
	public ResponseBase<Long> getIdByPhoneNum(@RequestBody SysUserReq req) {
		ResponseBase<Long> resp = new  ResponseBase<Long>();

		String userName  = req.getName();
		if(req == null || StringHelper.isEmpty(userName)){
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("参数错误");
			return resp;
		}


		SysUser user = sysUserService.getByPhoneNum(userName);
		if(user == null){
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("改手机号不存在");
			return resp;
		}

		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setResult(user.getId());
		return resp;
	}

	/**
	 * @Title: getSysUserById
	 * @Description: 根据id获取用户
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getSysUserById", method = RequestMethod.POST)
	public ResponseBase<SysUserMsg> getSysUserById(@RequestBody SysUserReq req) {

		ResponseBase<SysUserMsg> resp = new ResponseBase<SysUserMsg>();
		SysUserMsg sresp = new SysUserMsg();
		try {
			if (req == null || req.getId() == null
					|| (!sysUserService.existById(req.getId()))) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}

			SysUser sysUser = sysUserService.findById(req.getId());

			if (sysUser == null || sysUser.getId()==null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("用户不存在！");
				resp.setResult(sresp);
			}

			sresp = sysUserService.getRespUser(sysUser.getId());
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(sresp);

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: getSysUserById
	 * @Description: 根据id获取用户
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/updLevel", method = RequestMethod.POST)
	public ResponseBase<Boolean> updLevel(@RequestBody SysUserReq req) {



		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		if (req == null || req.getId() == null
				|| (!sysUserService.existById(req.getId()))) {
			resp.setResult(false);
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("参数不对：id is null！");
			return resp;
		}

		logger.info("userid = " + req.getId() + "  level = " + req.getLevel());

		SysUser user = sysUserService.findById(req.getId());

		if (user != null) {
			user.setLevel(req.getLevel());
			sysUserService.update(user);
		}

		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setResult(true);
		return resp;
	}

	/**
	 * @Title: getSysUserList
	 * @Description: 分页获取用户
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getSysUserList", method = RequestMethod.POST)
	public ResponseBase<List<SysUserMsg>> getSysUserList(
			@RequestBody SysUserReq req) {
		ResponseBase<List<SysUserMsg>> resp = new ResponseBase<List<SysUserMsg>>();

		if(req.getActUserId() == null){
			resp.setMsg("登录超时，请再次登录！");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}

		Long userId = req.getActUserId();
		SysUser actUse = sysUserService.findById(userId);

		if(actUse == null ){
			resp.setMsg("您登录所使用的账户不存在，请再次登录！");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}


		List<SysUserMsg> respList = new ArrayList<SysUserMsg>();

		HqlFilter hqlFilter = new HqlFilter();

		hqlFilter.addSql(" where 1=1 ");
		if (StringUtils.isNotEmpty(req.getName().trim())) {
			hqlFilter.addSql(" and (userPhone = '" + req.getName().trim()
					+ "' or userRealName like '%" + req.getName().trim() + "%' )");
		}

		if (req.getLevel() != null) {
			// hqlFilter.addEQFilter("level", req.getLevel());
			hqlFilter.addSql(" and level = " + req.getLevel());
		}

		if (req.getChannel() != null) {
			hqlFilter.addSql(" and channel = " + req.getChannel());
		}

		if (req.getIsLeave() != null && req.getIsLeave() == 1) {
			hqlFilter.addSql(" and LeaveTime is not null");
		}


		if(req.getDepId() != null && req.getDepId() != 0){
			Organization org = orgService.findById(req.getDepId());
			String orgCode = org.getCode();
			hqlFilter.addSql(" and userOrgCode like '" + orgCode + "%' ");
		}

		String endDateStr = req.getEndDate();
		String beginDateStr = req.getBeginDate();

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Date beginDate;
		Date endDate;

		try {
			// 增添日期筛选条件
			if (StringUtils.isNotEmpty(beginDateStr)) {
				beginDate = format.parse(beginDateStr);
				hqlFilter.addSql(" and registCts > " + beginDate.getTime());
			}

			if (StringUtils.isNotEmpty(endDateStr)) {
				endDate = format.parse(endDateStr);

				Long endTimeLong = endDate.getTime() + 60 * 60 * 24 * 1000;

				hqlFilter.addSql(" and registCts < " + endTimeLong);
			}
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			logger.info("order/list 日期格式转换错误");
			e1.printStackTrace();
		}

		// 是否绑卡
		if (req.getTieCard() != null) {
			hqlFilter.addSql(" and tieCard = " + req.getTieCard());
		}
		// 是否为理财师
		if (req.getIsInside() != null) {
			hqlFilter.addSql(" and isInside = " + req.getIsInside());
		}

		// 推荐码
		if (StringHelper.isNotEmpty(req.getRecommendCode().trim())) {
			hqlFilter.addSql(" and recommendCode = " + req.getRecommendCode());
		}


		// 如果是渠道录入人员，则只让其看到自己录入的人员信息
		if (sysUserRolesService.isChannelRegis(userId)) {
			hqlFilter.addSql(" and creator = " + userId);

		}else if(sysUserRolesService.isDepLeader(userId)){
			String appendSql = " channel = -1 ";
			List<Integer> channelIdList = orgNewService.getDepLeaderChannelStrList(userId);

			for (Integer channelId : channelIdList) {
				logger.info(" channelId ={}", channelId);
				appendSql += " or channel = " + channelId;
			}

			hqlFilter.addSql(" and isInside = 1 and ( " +  appendSql  + " )");

		}else if (sysUserRolesService.isTeamLeader(req.getActUserId())){
			logger.info("user is team leader");

			Organization org = orgService.findById(actUse.getOrgId());

			//如果是某个团队的负责人
			String code = orgService.getOrgLeaderCodeByOrgId(org.getId());

			hqlFilter.addSql(" and isInside = 1 and userOrgCode like '" + code + "%' ");
		}else if (sysUserRolesService.isAuth(req.getActUserId())){
			hqlFilter.addSql(" and isInside = 1");
		}

		logger.info("get sysuser list hqlfilter = " + hqlFilter.getWhereAndOrderHql());



		try {

			logger.info("sysuser request page size = {}", req.getPageSize());
			if (req.getPageSize() > 1000) {
				Long size = userViesService.countByFilter(hqlFilter);
				resp.setSize(size);
				resp.setResult(respList);
			} else {
				List<UserView> retList = userViesService.findByFilter(hqlFilter,
						req.getCurPage(), req.getPageSize());

				if(retList == null || retList.size() == 0){
					resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
					resp.setMsg("数据不存在！");
					return resp;
				}
				respList = retList.parallelStream()
						.map(userView -> sysUserService.getRespUser(userView.getUserId()))
								.filter(sresp -> sresp != null)
						.collect(Collectors.toList());

				resp.setSize(retList.size());
				resp.setResult(respList);
				resp.setResultCode(StatusCode.SUCCESS.key());
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		return resp;
	}

	/**
	 * 新增用户，并送加息券
	 * 
	 * @Title: saveSysUser
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/saveSysUser", method = RequestMethod.POST)
	public ResponseBase<SysUser> saveSysUser(@RequestBody SysUserReq req) {
		ResponseBase<SysUser> resp = new ResponseBase<SysUser>();
		try {
			String name = req.getName().trim();

			if(name == null || name.trim().length() != 11){
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("手机号格式不正确，请输入11位手机号！");
				return resp;
			}

			SysUser dbUser = sysUserService.getByAccount(req.getName().trim());

			if (dbUser == null) {
				SysUser model = new SysUser();
				String sysRoleIds = req.getSysRoleIds();
				req.setSysRoleIds(null);
				ReqToModelHelper.copyReqValueToModel(req, model);
				if (StringUtils.isNotBlank(req.getBirthday())) {
					Long birthday = DateHelper.stringToDate(req.getBirthday())
							.getTime();
					model.setBirthday(birthday);
				}
				if (StringUtils.isNotBlank(req.getEntryTime())) {
					Long entryTime = DateHelper
							.stringToDate(req.getEntryTime()).getTime();
					model.setEntryTime(entryTime);
				}

				model.setName(name);
				model.setPwd(MD5Crypter.md5Encrypt(req.getPwd()));
				model.setOnType(ConstantUser.USER_NOT_LEAVE); // 在职
				model.setIsInside(1); //是理财师
				model.setCreator(req.getActUserId());// 设置创建人员为操作人员
				// 如果客户有组织架构，且不为无主客户，则推荐码改为自己
				if (model.getOrgId() != null
						&& !(model.getOrgId()
								.equals(ConstantUser.USER_ORG_WUZHU))) {
					model.setRecommendCode(model.getName());
					model.setChannel(orgService.getChannelById(model.getOrgId()));
				} else {
					model.setChannel(ConstantUserChannel.USER_CHANNEL_WUZHU);
				}

				Long retId = sysUserService.add(model);

				if (retId != null) {
					if (StringUtils.isNotBlank(sysRoleIds)) {
						saveOrUpdateSysUserRoles(sysRoleIds, req.getName());
					}

					SysUser user = sysUserService.findById(retId);
					if (user != null) {
						// 判断是否送加息券
						checkSendCards(user);
					}

					model.setId(retId);
					resp.setResult(model);
					resp.setResultCode(StatusCode.SUCCESS.key());
					resp.setMsg("添加成功");
				} else {
					resp.setResultCode(StatusCode.ERROR.key());
					resp.setMsg("添加失败");
				}
			} else {
				resp.setResultCode(StatusCode.DATA_EXISTS.key());
				resp.setMsg("账号已存在");
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 渠道录入用户
	 * 
	 * @Title: saveSysUser
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/saveSysUserByChannelRegis", method = RequestMethod.POST)
	public ResponseBase<SysUser> saveSysUserByChannel(
			@RequestBody SysUserReq req) {
		ResponseBase<SysUser> resp = new ResponseBase<SysUser>();

		Integer orgId = req.getOrgId();
		String name = req.getName().trim();
		Long actUserId = req.getActUserId();

		logger.info("saveSysUserByChannelRegis name={}, orgId={}，actUserId={}", name, orgId, actUserId);

		try {
			if(orgId == null || StringHelper.isEmpty(name)){
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("参数错误，添加用户失败！");
				return resp;
			}

			if(actUserId == null){
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("登录超时，请重新登录后再进行尝试！");
				return resp;
			}

			if(name == null || name.trim().length() != 11){
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("手机号格式不正确，请输入11位手机号！");
				return resp;
			}

			// 01查看用户是否具有权限
			SysUser actUser = sysUserService.findById(req.getActUserId());

			if (actUser == null
					|| !sysUserRolesService.isChannelRegis(actUser.getId())) {
				resp.setResultCode(StatusCode.DATA_EXISTS.key());
				resp.setMsg("您不具备该权限，请退出！");
				return resp;
			}

			SysUser dbUser = sysUserService.getByAccount(name);

			// 02查看用户是否存
			if (dbUser != null) {
				String depFullName = "";
				if (dbUser.getOrgId() != null) {
					Organization org = orgService.findById(dbUser.getOrgId());
					if (org != null && StringHelper.isNotEmpty(org.getFlag02())) {
						depFullName = org.getFlag02();
					}
				}
				resp.setResultCode(StatusCode.DATA_EXISTS.key());

				if(dbUser.getIsInside() != null && dbUser.getIsInside() == 1){
					resp.setMsg("账号已存在, 目前的职务是：\n" + depFullName);
				}else{
					resp.setMsg("账号已存在");
				}

				return resp;
			}

			SysUser model = new SysUser();

			ReqToModelHelper.copyReqValueToModel(req, model);
			model.setName(name);
			model.setPwd(MD5Crypter.md5Encrypt("123456"));
			model.setOnType(ConstantUser.USER_NOT_LEAVE); // 在职
			model.setIsInside(1); //是內部員工
			model.setCreator(req.getActUserId());// 设置创建人员为操作人员
			model.setRecommendCode(model.getName());

			Organization org = orgNewService.findById(orgId);

			model.setChannel(org.getChannel());
			model.setOrgId(orgId);

			Long retId = sysUserService.add(model);

			logger.info("添加成功，用户id={}", retId);
			if (retId != null) {
				SysUser user = sysUserService.findById(retId);
				if (user != null) {
					// 判断是否送加息券
					checkSendCards(user);
				}
				model.setId(retId);
				resp.setResult(model);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("添加成功");
			} else {
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("添加失败");
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: saveOrUpdateSysUserRoles
	 * @Description: 保存或更新用户角色关联表信息
	 * @param sysRoleIds
	 * @param account
	 */
	private void saveOrUpdateSysUserRoles(String sysRoleIds, String account) {
		try {
			if (StringUtils.isNotEmpty(account)) {
				String[] roleIds = sysRoleIds.split(",");
				List<SysUserRoles> sysUserRolesList = sysUserRolesService
						.getByUserAccount(account);
				// 先删除后添加，效率更快
				for (SysUserRoles sysUserRole : sysUserRolesList) {
					sysUserRolesService.delete(sysUserRole.getId());
				}
				for (String roleid : roleIds) {
					SysUserRoles sysUserRoles = new SysUserRoles();
					sysUserRoles.setRoleId(Long.parseLong(roleid));
					sysUserRoles.setAccount(account);
					sysUserRolesService.add(sysUserRoles);
				}
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * @Title: saveOrUpdateSysUserRoles
	 * @Description: 保存或更新用户角色关联表信息
	 * @param account
	 */
	private void deleteAllSysUserRoles(String account) {
		try {
			if (StringUtils.isNotEmpty(account)) {
				List<SysUserRoles> sysUserRolesList = sysUserRolesService
						.getByUserAccount(account);
				// 先删除后添加，效率更快
				for (SysUserRoles sysUserRole : sysUserRolesList) {
					sysUserRolesService.delete(sysUserRole.getId());
				}
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * @Title: initSysUserPwd
	 * @Description: TODO 初始化用户密码
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/initSysUserPwd", method = RequestMethod.POST)
	public ResponseBase<SysUser> initSysUserPwd(@RequestBody SysUserReq req) {
		ResponseBase<SysUser> resp = new ResponseBase<SysUser>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			SysUser model = sysUserService.findById(req.getId());
			model.setPwd(MD5Crypter.md5Encrypt(initpwd));

			sysUserService.update(model);

			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("密码初始化成功！用户:" + model.getRealName() + "["
					+ model.getName() + "]");

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}


    /**
     * @param
     * @Title: changeSysUserPwd
     */
    @ResponseBody
    @RequestMapping(value = "/changeSysUserPwd", method = RequestMethod.POST)
    public ResponseBase<SysUser> changeSysUserPwd(@RequestBody SysUserChangePwdReq req) {
        ResponseBase<SysUser> resp = new ResponseBase<SysUser>();
        try {
            if (req == null
                    || req.getId() == null
                    || StringUtils.isBlank(req.getOldPwd())
                    || StringUtils.isBlank(req.getNewPwd()) ) {
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("参数不对： 关键字段不能为空!");
                return resp;
            }
            SysUser user = sysUserService.findById(req.getId());

            if(user == null){
                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("用户不存在");
                return resp;
            }

            String oldPwdMd5 = MD5Crypter.md5Encrypt(req.getOldPwd());
            if (!user.getPwd().equalsIgnoreCase(oldPwdMd5)) {
                logger.error("{} diff {}", user.getPwd(), oldPwdMd5);

                resp.setResultCode(StatusCode.PARAM_ERROR.key());
                resp.setMsg("原密码错误，请重新输入!");
                return resp;
            }

            user.setPwd(MD5Crypter.md5Encrypt(req.getNewPwd()));

            sysUserService.update(user);

            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setMsg("密码修改成功！用户:" + user.getRealName() + "[" + user.getName() + "]");

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resp.setMsg("操作异常，请重试");
            resp.setResultCode(StatusCode.EXCEPTION.key());
        }
        return resp;
    }

	/**
	 * @Title: deleteSysUser
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteSysUser", method = RequestMethod.POST)
	public ResponseBase<SysUser> deleteSysUser(@RequestBody SysUserReq req) {
		ResponseBase<SysUser> resp = new ResponseBase<SysUser>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			SysUser model = sysUserService.findById(req.getId());
			SysUser ret = sysUserService.delete(req.getId());

			if (ret != null) {
				resp.setResult(ret);

				List<SysUserRoles> sysUserRolesList = sysUserRolesService
						.getByUserAccount(model.getName());
				// 清除用户角色关联表信息
				for (SysUserRoles sysUserRole : sysUserRolesList) {
					sysUserRolesService.delete(sysUserRole.getId());
				}
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("删除成功");
			} else {
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("删除失败");
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: saveSysUserRole
	 * @Description: 保存添加用户-角色表信息
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/saveSysUserRole")
	public ResponseBase<SysUser> saveSysUserRole(
			@RequestBody SysUserRolesReq req) {
		ResponseBase<SysUser> resp = new ResponseBase<SysUser>();
		try {
			if (StringUtils.isNotEmpty(req.getAccount())) {
				String[] accountArr = req.getAccount().split(",");
				for (String account : accountArr) {
					saveOrUpdateSysUserRoles(req.getRoleIds(), account);
				}

			} else {
				resp.setMsg("请选择用户！");
				resp.setResultCode(StatusCode.ERROR.key());
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/updateSysUser", method = RequestMethod.POST)
	public ResponseBase<SysUser> updateSysUser(@RequestBody SysUserReq req) {
		ResponseBase<SysUser> resp = new ResponseBase<SysUser>();
		try {

			if (req.getActUserId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录！");
				return resp;
			}

			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：订单 id 为空！");
				return resp;
			}

			String sysRoleIds = req.getSysRoleIds();
			req.setSysRoleIds(null);
			SysUser model = sysUserService.findById(req.getId());

			// 保存到log中
			LogUtil logRecord = new LogUtil();

			logRecord.setActUserId(req.getActUserId());
			logRecord.setType(ConstantLog.LOG_TYPE_USER_BASE);
			String realName = "";
			if (StringHelper.isNotEmpty(model.getRealName())) {
				realName = model.getRealName();
			}
			logRecord.setChgDesc("修改用户基本信息 用户名   : " + realName);
			logRecord.setRecordId(req.getId());
			logRecord.setUserId(req.getId());

			// 在日志表中保存修改之前的镜像
			String beforeImgStr = JsonUtils.toJson(sysUserService
					.getRespUser(model.getId()));
			logRecord.setBeforeImg(beforeImgStr);

			// 公开属性，管理员跟员工都可以修改
			model.setRealName(req.getRealName());

			if (StringUtils.isNotBlank(req.getBirthday())) {
				Long birthday = DateHelper.stringToDate(req.getBirthday())
						.getTime() + 12 * 60 * 60 * 1000;
				model.setBirthday(birthday);
			}

			// 更改生日
			if (StringHelper.isNotEmpty(req.getIdentity())
					&& model.getBirthday() == null) {
				String birthday = IdcardUtils.getBirthByIdCard(req
						.getIdentity());
				Long birthDayLong = DateUtil.transferStringToLong(birthday) + 12 * 60 * 60 * 1000;
				model.setBirthday(birthDayLong);
			}
			model.setIdentity(req.getIdentity());
			model.setAge(req.getAge());
			model.setHealthStatus(req.getHealthStatus());

			// 级别
			model.setLevel(req.getLevel());

			// 修改组织架构id, 如果组织架构不为空，则推荐码为用户自己的手机号，推荐用户id为用户自己的id
			logger.info("用户组织架构更改，old orgId={}, new orgId={}",
						model.getOrgId(), req.getOrgId());
			model.setOrgId(req.getOrgId());

			Organization org = orgService.findById(req.getOrgId());
			model.setChannel(org.getChannel());

			/*
			if (!(req.getOrgId().equals(ConstantUser.USER_ORG_WUZHU))) {
				model.setChannel(orgService.getChannelById(req.getOrgId()));
				model.setRecommendCode(model.getName());
				model.setRecommendId(model.getId());
				// 赠送加息券
				//userCardService.sendCardToUser(model);
				//couponService.sendJXQToUser(model.getId());
			}
			*/

			model.setIsInside(req.getIsInside());

			//如果是理财师
			if(req.getIsInside() == 1){
				model.setRecommendCode(model.getName());
			}

			if (StringHelper.isNotEmpty(req.getEntryTime())) {
				Long entryTime = DateHelper.stringToDate(req.getEntryTime())
						.getTime();
				model.setEntryTime(entryTime);
			}

			if (StringHelper.isNotEmpty(req.getLeaveTime())) {
				Long leaveTime = DateHelper.stringToDate(req.getLeaveTime())
						.getTime();
				model.setLeaveTime(leaveTime);
				model.setOnType(ConstantUser.USER_LEAVE); // 离职
				// 计算在职时间，以天
				long days = 0l;
				if (model.getEntryTime() != null) {
					String entryTimes = DateHelper.getAssignTimestampByFormat(
							new Timestamp(model.getEntryTime()), "yyyy-MM-dd");
					String leaveTimes = DateHelper.getAssignTimestampByFormat(
							new Timestamp(model.getLeaveTime()), "yyyy-MM-dd");
					days = DateHelper.between(entryTimes, leaveTimes, 3);
				}
				String onJobTime = days + "天";
				model.setOnJobTime(onJobTime);

				// 如果理财师离职，该理财师 名下其直属客户的推荐码置空，由该渠道省总自由分配理财师，其直属客户的客户组织架构不变
//				sysUserService.cleanRecommandCordByCode(model.getName(),
//						req.getActUserId());

			} else {
				// 未离职
				model.setOnType(ConstantUser.USER_NOT_LEAVE);
				model.setLeaveTime(null);
			}

			sysUserService.update(model);

			if (StringUtils.isNotBlank(sysRoleIds)) {
				saveOrUpdateSysUserRoles(sysRoleIds, model.getName());
			}else{
				deleteAllSysUserRoles(model.getName());
			}

			// 在日志表中保存修改之后的镜像
			String afterImgStr = JsonUtils.toJson(sysUserService
					.getRespUser(model.getId()));
			logRecord.setAfterImg(afterImgStr);
			// 加入日志表中
			logService.add(logRecord);

			resp.setResult(model);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}


	@ResponseBody
	@RequestMapping(value = "/updateSysUserCode", method = RequestMethod.POST)
	public ResponseBase<SysUser> updateSysUserCode(@RequestBody SysUserReq req) {
		ResponseBase<SysUser> resp = new ResponseBase<SysUser>();

		try {

			logger.info("updateSysUserCode 操作者的id = {}, 操作对象的id = {}, 新的推荐码  = {}", req.getActUserId(), req.getId(), req.getRecommendCode());


			if (req == null || req.getActUserId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录！");
				return resp;
			}

			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：部分参数为空");
				return resp;
			}

			Long actUserId = Long.valueOf(req.getActUserId());
			if (sysUserService.findById(actUserId) == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：操作人不存在！");
				return resp;
			}

			SysUser user = sysUserService.findById(req.getId());
			if(user == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：被修改用户不存在！");
				return resp;
			}

			Boolean needSendCard = false;
			String recommendCode = req.getRecommendCode();

			if(StringHelper.isNotEmpty(recommendCode)){
				SysUser finUser = sysUserService.getByPhoneNum(recommendCode);
				if(finUser != null && finUser.getIsInside() == 1){
					needSendCard = sysUserService.checkNeedSendRegistCard(req.getId());
				}
			}


			CheckInfo checkInfo = sysUserService.updateRecommandCode(req.getRecommendCode(), req.getId(), actUserId);

			if(!checkInfo.getResult()){
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg(checkInfo.getResultMsg());
			}else{
				user = sysUserService.findById(req.getId());
				resp.setResult(user);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("修改成功");
				if(needSendCard) {
					resp.setMsg("首次从无主客户变成有主客户，已成功赠送一张加息券。");
				}
			}
			return resp;
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}


	@ResponseBody
	@RequestMapping(value = "/mutiUpdateSysUserCode", method = RequestMethod.POST)
	public ResponseBase<Boolean> mutiUpdateSysUserCode(@RequestBody SysUserReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();

		try {

			logger.info("mutiUpdateSysUserCode 操作者的id = {}, 操作对象的id = {}, 新的推荐码  = {}", req.getActUserId(), req.getIds(), req.getRecommendCode());


			if (req == null|| req.getActUserId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录！");
				return resp;
			}

			Long actUserId = Long.valueOf(req.getActUserId());
			if (sysUserService.findById(actUserId) == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：操作人不存在！");
				return resp;
			}

			if (StringHelper.isEmpty(req.getIds()) || StringHelper.isEmpty(req.getRecommendCode())) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：部分参数为空");
				return resp;
			}


			SysUser finUser = sysUserService.getByPhoneNum(req.getRecommendCode().trim());
			if(finUser == null || finUser.getIsInside() == 0){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("所收入的推荐码不是理财师，此次修改失败！");
				return resp;
			}


			String[] arrayIds = req.getIds().split(",");


			List<String> userIdList = Arrays.asList(arrayIds);

			String recommandCode = req.getRecommendCode();

			List<CheckInfo> errResultList = userIdList.parallelStream()
					  .map(userIdStr -> Long.valueOf((String)userIdStr))
					  .map(userIdLong -> sysUserService.updateRecommandCode(recommandCode, userIdLong, actUserId) )
					  .filter(checkInfo -> checkInfo.getResult() == false)
					  .collect(Collectors.toList());
			getResponse(resp, errResultList);

			return resp;
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	private void getResponse(ResponseBase<Boolean> resp, List<CheckInfo> errResultList) {
		if(errResultList == null || errResultList.size() == 0){
            resp.setResult(true);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setMsg("修改成功");
        }else{
            resp.setResult(false);
            resp.setResultCode(StatusCode.ERROR.key());
            resp.setMsg("部分修改失败");
        }
	}

	@ResponseBody
	@RequestMapping(value = "/mutiUpdateSysUserOrg", method = RequestMethod.POST)
	public ResponseBase<Boolean> mutiUpdateSysUserOrg(@RequestBody SysUserReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();

		try {

			logger.info("mutiUpdateSysUserOrg 操作者的id = {}, 操作对象的id = {}, 新的组织架构ID  = {}", req.getActUserId(), req.getIds(), req.getOrgId());

			if (req == null|| req.getActUserId() == null || req.getOrgId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("登录超时，请重新登录！");
				return resp;
			}

			Long actUserId = Long.valueOf(req.getActUserId());
			if (sysUserService.findById(actUserId) == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：操作人不存在！");
				return resp;
			}



			if (StringHelper.isEmpty(req.getIds())) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：部分参数为空");
				return resp;
			}

			Organization org = orgService.findById(req.getOrgId());
			if(org == null){
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：新的组织架构不存在");
				return resp;
			}


			String[] arrayIds = req.getIds().split(",");


			List<String> userIdList = Arrays.asList(arrayIds);

			Integer chgCustomer = req.getChgCustomer();

			List<CheckInfo> errResultList = userIdList.parallelStream()
					.map(userIdStr -> Long.valueOf((String)userIdStr))
					.map(userIdLong -> sysUserService.updateOrgId(org, userIdLong, actUserId, chgCustomer) )
					.filter(checkInfo -> checkInfo.getResult() == false)
					.collect(Collectors.toList());

			getResponse(resp, errResultList);

			return resp;
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

    // 理财师离职,批量修改旗下所有用户
    @ResponseBody
    @RequestMapping(value = "/multiUpdateOrgForFinancialLeave", method = RequestMethod.POST)
    public ResponseBase<String> multiUpdateOrgForFinancialLeave(@RequestBody FinancialLeaveDTO req) {
        ResponseBase<String> result = new ResponseBase<String>();

        SysUser operator = sysUserService.findById(req.operatorId);
        if (operator == null) {
            result.setResultCode(StatusCode.PARAM_ERROR.key());
            result.setMsg("操作人" + req.operatorId + "不存在或登录超时！");
            return result;
        }

        SysUser financial = sysUserService.findById(req.financialId);
        if (financial == null) {
            result.setResultCode(StatusCode.PARAM_ERROR.key());
            result.setMsg("理财师" + req.financialId + "不存在！");
            return result;
        }

        List<SysUser> relatedUsers = sysUserService.getUserByRecommendCode(financial.getName());

        List<CheckInfo> errResultList = relatedUsers.parallelStream()
                .map(
                        user -> sysUserService.updateRecommandCode("", user.getId(), operator.getId())
                )
                .filter(checkInfo -> !checkInfo.getResult())
                .collect(Collectors.toList());

        if (errResultList == null || errResultList.size() == 0) {
            result.setResultCode(StatusCode.SUCCESS.key());
            result.setSize(relatedUsers.size());
            result.setMsg("修改成功!");
        } else {
            result.setResultCode(StatusCode.ERROR.key());
            result.setSize(errResultList.size());
            result.setMsg("部分修改失败!");
        }

        return result;
    }


    // 离职
	@ResponseBody
	@RequestMapping(value = "/leave", method = RequestMethod.POST)
	public ResponseBase<SysUser> leave(@RequestBody SysUserReq req) {
		ResponseBase<SysUser> resp = new ResponseBase<SysUser>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			SysUser model = sysUserService.findById(req.getId());
			model.setOnType(ConstantUser.USER_NOT_LEAVE); // 离职
			if (StringUtils.isNotBlank(req.getLeaveTime())) {
				Long leaveTime = DateHelper.stringToDate(req.getLeaveTime())
						.getTime();
				model.setLeaveTime(leaveTime);
			}
			sysUserService.update(model);

			resp.setResult(model);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	// Excel导入
	@ResponseBody
	@RequestMapping(value = "/import")
	public ResponseBase<Boolean> importExcel() {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		try {
			String fileFullName = "C:\\Users\\jeff\\Desktop\\userInfo\\userInfo.xls";
			// req.getUserExcelFullPath();

			List<SysUser> userList = ReadExcelToUserDB.readExcel(fileFullName);
			System.out.println("userList size = " + userList.size());

			for (SysUser user : userList) {
				
				SysUser model = sysUserService.getByAccount(user.getName());
				if (model == null) {
					logger.info("user will add into DB name={}", user.getName());
					user.setCreator(Long.valueOf("72344298037646"));
					user.setPwd(MD5Crypter.md5Encrypt(initpwd));
					user.setChannel(orgService.getChannelById(user.getOrgId()));
					user.setRecommendCode(user.getName());

					Long userId = sysUserService.add(user);
					// 发放加息券
					user.setId(userId);

					//userCardService.sendCardToUser(user);
					couponService.sendJXQToUser(userId);
				} else {
					logger.info("user exist in DB, will update name={}",
							user.getName());
					// 如果用户存在,则修改

					// 如果用户原有的推荐码不是自己，则送加息券
					String recommendCode = model.getRecommendCode();
					if (!sysUserService.isFinUserByPhoneNum(recommendCode)) {
						//userCardService.sendCardToUser(model);
						couponService.sendJXQToUser(model.getId());
					}

					model.setRealName(user.getRealName());
					model.setIdentity(user.getIdentity());
					model.setOrgId(user.getOrgId());
					model.setChannel(orgService.getChannelById(user.getOrgId()));
					model.setRecommendCode(user.getName());
					sysUserService.update(model);
				}
			}

			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setResult(false);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	// Excel导入
	@ResponseBody
	@RequestMapping(value = "/impChg", method = RequestMethod.GET)
	public ResponseBase<Boolean> impChg(@RequestParam String  fileFullName  ) {
		fileFullName = filePath + "/" + fileFullName;
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		try {

			logger.info(" sysuser impChg fileFullName={}", fileFullName);

			List<UserChangeInfo> userList = ReadExcelToUserChg.readExcel(fileFullName);
			System.out.println("userList size = " + userList.size());


			for (UserChangeInfo userChg : userList) {

				SysUser user  = sysUserService.getByPhoneNum(userChg.getName());
				if(user != null){
					userChg.setUserId(user.getId());
				}else{
					logger.info("old user is null name ={}", userChg.getName());
				}

				String orgFullName = userChgService.getNewOrgFullName(userChg);
				userChg.setNewOrgFullName(orgFullName);
				userChgService.add(userChg);
			}

			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setResult(false);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 批量修改用户
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/startChg", method = RequestMethod.GET)
	public ResponseBase<Boolean> startChg( ) {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		try {

			logger.info(" sysuser startChg begin");

			List<UserChangeInfo> userChangeList = userChgService.getAll();
			for(UserChangeInfo chgInfo:userChangeList){
				String fullName = chgInfo.getNewOrgFullName();


				orgNewService.checkOrg(fullName);
				Organization suerOrg = orgNewService.getByFullName(fullName);
				if(suerOrg == null){
					System.out.println("<----------------------error----------------------------> check 02, org is not exist  name = " +  fullName);
				}else{
					chgInfo.setNewOrgId(suerOrg.getId());
					chgInfo.setNewParId(suerOrg.getParentID());

					chgInfo.setNewChannelId(getChannelId(chgInfo.getNewChannelName()));
					userChgService.update(chgInfo);
				}
			}

			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setResult(false);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		logger.info(" sysuser startChg end");
		return resp;
	}

	/**
	 * 批量修改用户
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updUserOrg", method = RequestMethod.GET)
	public ResponseBase<Boolean> updUser( ) {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		try {

			logger.info(" updUser user begin");

			List<UserChangeInfo> userChangeList = userChgService.getAll();
			for(UserChangeInfo chgInfo:userChangeList){
				SysUser user = sysUserService.findById(chgInfo.getUserId());
				if(user == null){
					logger.info("<-----------------error---------------> user is not exist");
				}else{
					chgUser(user,chgInfo.getNewOrgId(), chgInfo.getNewChannelId());
				}
			}
			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setResult(false);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		logger.info(" updUser user end");
		return resp;
	}

	/**
	 * 批量修改用户
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updCustomerOrg", method = RequestMethod.GET)
	public ResponseBase<Boolean> updCustomerOrg( ) {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		try {

			logger.info(" updUser user begin");

			List<SysUser> sysUsersList = sysUserService.getAll();

			for(SysUser user:sysUsersList){
				if(user.getIsInside() == 0  && StringHelper.isNotEmpty(user.getRecommendCode())){
					SysUser finUser = sysUserService.getByPhoneNum(user.getRecommendCode());
					if(finUser != null && finUser.getIsInside() == 1){
						chgUser(user,finUser.getOrgId(), finUser.getChannel());
					}
				}
			}
			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setResult(false);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		logger.info(" updUser user end");
		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public void upload(HttpServletRequest request, HttpServletResponse response)
			throws FileUploadException, IOException, ServletException {

	}

	/**
	 * 更新用户的所属的省份、生日、和渠道
	 * 
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateAll", method = RequestMethod.GET)
	public ResponseBase<Boolean> updAll() {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();

		HqlFilter hqlfilter = new HqlFilter();

		List<SysUser> userList = sysUserService.findByFilter(hqlfilter);

		if (userList == null || userList.size() == 0) {
			resp.setResult(false);
			resp.setResultCode(ResultCode.FAILED.getCode());
			resp.setMsg("用户不存在！");
			return resp;
		}

		for (SysUser user : userList) {
			// 更改客户生日和省份
			if (StringHelper.isNotEmpty(user.getIdentity())) {

				String identity = user.getIdentity();

				// 更改客户生日
				String birthday = IdcardUtils.getBirthByIdCard(identity);
				if (user.getBirthday() == null) {
					Long birthDayLong = DateUtil.transferStringToLong(birthday);
					user.setBirthday(birthDayLong);
				}

				if (StringHelper.isEmpty(user.getLocation())) {
					String location = IdcardUtils.getCityByIdCard(identity);
					if (StringHelper.isEmpty(location)) {
						location = IdcardUtils.getProvinceByIdCard(identity);
					}
					user.setLocation(location);
				}

			}

			// 如果推荐码不为空， 并且用户的channel 为空， 则判断用户的渠道
			if (StringHelper.isNotEmpty(user.getRecommendCode())
					&& user.getChannel() == null) {
				SysUser finUser = sysUserService.getByPhoneNum(user
						.getRecommendCode());
				if (finUser != null) {
					if (finUser.getChannel() != null) {
						user.setChannel(finUser.getChannel());
					} else if (finUser.getOrgId() != null) {
						Integer channel = orgService.getChannelById(finUser
								.getOrgId());
						user.setChannel(channel);
					} else {
						user.setChannel(ConstantUserChannel.USER_CHANNEL_WUZHU);
					}
				} else {
					user.setChannel(ConstantUserChannel.USER_CHANNEL_WUZHU);
				}
			}

			// 如果推荐码为空， 则直接判断为无主客户
			if (StringHelper.isEmpty(user.getRecommendCode())) {
				user.setChannel(ConstantUserChannel.USER_CHANNEL_WUZHU);
			}
			sysUserService.update(user);

		}
		resp.setResult(true);
		resp.setResultCode(ResultCode.SUCC.getCode());
		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/addCard", method = RequestMethod.POST)
	public void addCard(@RequestBody SysUserReq req){
			if(req != null) {
				Long userId = req.getUserId();
				if (userId != null && sysUserService.existById(userId)) {
					couponService.sendJXQToUser(userId);
					logger.info("will send card to user , userId={}", userId);
				}
			}

	}


	@ResponseBody
	@RequestMapping(value = "/getFinUser", method = RequestMethod.POST)
	public ResponseBase<Map<String, Object>> getFinUser(@RequestBody SysUserReq req){
		ResponseBase<Map<String, Object>> resp = new ResponseBase<Map<String, Object>>();

		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (req == null || req.getUserId() == null) {
			resp.setResult(null);
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
			return resp;
		}

		Long userId = req.getUserId();

		SysUser user = sysUserService.findById(userId);

		if (StringHelper.isEmpty(user.getRecommendCode())) {
			logger.info("用户推荐码是空的，没有理财师");
			resultMap.put("cfpName", "");
			resultMap.put("cfpPhone", "");;
			resp.setResult(resultMap);
			resp.setResultCode(ResultCode.SUCC.getCode());
			return resp;
		}

		SysUser finuser = sysUserService.getByPhoneNum(user.getRecommendCode());
		if (finuser == null || finuser.getIsInside() != 1) {
			resultMap.put("cfpName", "");
			resultMap.put("cfpPhone", "");;
			resp.setResult(resultMap);
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
			logger.info("用户理财师不存在");
			return resp;
		} else {

			if (StringHelper.isNotEmpty(finuser.getRealName())) {
				logger.info("用户理财师姓名不为空");
				resultMap.put("cfpName", finuser.getRealName());
			}else{
				logger.info("用户理财师姓名为空");
				resultMap.put("cfpName", "");
			}

			resultMap.put("cfpPhone", finuser.getName());


			resp.setResult(resultMap);

			resp.setResultCode(ResultCode.SUCC.getCode());
			return resp;
		}
	}

	/**
	 * 销户
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/closeAccount",method = RequestMethod.POST)
	public ResponseBase<SysUser> closeAccount(@RequestBody CloseAccountReq req){
		ResponseBase<SysUser> result = new ResponseBase<>();
		logger.info("will start closeAccount userId[{}]",req.getUserId());
		SysUser operator = sysUserService.findById(req.getActUserId());
		if(operator == null){
			result.setMsg("登录超时，请再次登录！");
			result.setResultCode(StatusCode.PARAM_ERROR.key());
			return result;
		}
		SysUser user = sysUserService.findById(req.getUserId());
		if(user == null || user.getCloseAccount()==1){
			result.setMsg("用户不存在,销户失败！");
			result.setResultCode(StatusCode.DATA_NOTEXISTS.key());
			return result;
		}

		try {
			CheckInfo checkInfo = safetyService.checkCodeErrorNum(req.getActUserId());
			if(!checkInfo.getResult()){
				logger.error("销户二重验证错误已超过5次，操作人ID：{}",req.getActUserId());
				result.setResultCode(StatusCode.PARAM_ERROR.key());
				result.setMsg(checkInfo.getResultMsg());
				return result;
			}

			checkInfo = safetyService.checkCode(req.getCode01(),req.getCode02(),ConstantSafety.SAFETY_CLOSE_ACCOUNT);
			if(!checkInfo.getResult()){
				logger.error("销户二重验证验证码错误.操作人ID:{}",req.getActUserId());
				safetyService.updateCodeErrorNum(req.getActUserId());
				result.setResultCode(StatusCode.PARAM_ERROR.key());
				result.setMsg(checkInfo.getResultMsg());
				return result;
			}

			//检查是否有在途订单
			if(orderService.countInTransitOrder(req.getUserId())>0L){
				logger.info("用户:{}有在途订单，销户失败，操作人ID:{}",req.getUserId(),req.getActUserId());
				result.setResultCode(StatusCode.ERROR.key());
				result.setMsg("用户:"+user.getRealName()+"有在途订单，销户失败");
				return  result;
			}

			//检查盈米是否已销户
			String yingMiInfo = sysUserContext.getYingMiAccountIf(user);
			JSONObject jsonObject = JSON.parseObject(yingMiInfo);
			if(jsonObject != null && jsonObject.containsKey("active") && jsonObject.getIntValue("active") == 1){
				logger.info("用户:{}盈米还没销户，销户失败，操作人ID:{}",req.getUserId(),req.getActUserId());
				result.setResultCode(StatusCode.ERROR.key());
				result.setMsg("用户:"+user.getRealName()+"在盈米还没有销户，本次销户失败");
				return  result;

			}

			//检查金账户里是否还有余额
			AccountBalance balance = sysUserService.getBalance(req.getUserId());
			if(balance == null){
				logger.info("get user balance error");
				result.setResultCode(StatusCode.ERROR.key());
				result.setMsg("查询用户余额异常，请重试");
				return result;
			}
			if(balance.getCt_balance().compareTo(new BigDecimal(0))>0){
				logger.info("用户:{}金账户还有余额{}元，销户失败，操作人ID:{}",req.getUserId(),balance.getCt_balance(),req.getActUserId());
				result.setResultCode(StatusCode.ERROR.key());
				result.setMsg("用户:"+user.getRealName()+"金账户还有余额，销户失败");
				return result;
			}

			/*检查通过，下面是销户的操作*/

			//把客户的所有银行卡都改为解卡状态
			paymentService.ChangeAllCardStatus(req.getUserId(),0);

			//如果是理财师，把名下所有客户修改为无主客户并清空推荐码
			if(!sysUserContext.updateCustomStatus(user,operator.getId())){
				result.setResultCode(StatusCode.ERROR.key());
				result.setMsg("修改客户状态部分失败，销户失败");
				return  result;
			}

			//清空权限角色
			sysUserRolesService.deleteByUserAccount(user.getName());

			//最后更新用户表销户状态和保存记录
			updateAndSaveCloseAccountLog(user,operator.getId());

			//app踢出被销户的用户
			RedisCilent.delKey(CacheConstants.UserLog_Token+user.getId());

			result.setResult(user);

		}catch (Exception e){
			logger.error("销户异常!",e);
			result.setResultCode(StatusCode.EXCEPTION.key());
			result.setMsg("系统异常");
		}

		return result;
	}

	/**
	 * 导出数据到Excel表
	 * @param response
	 * @param name 姓名
	 * @param level 用户级别
	 * @param channel 渠道
	 * @param isLeave 是否离职
	 * @param depId 部门ID
	 * @param beginDateStr 注册时间开始区间
	 * @param endDateStr 注册时间结束区间
	 * @param tieCard 是否绑卡
	 * @param isInside 是否理财师
	 * @param recommendCode
	 */
	@ResponseBody
	@RequestMapping(value = "/excel",method = RequestMethod.GET)
	public void excelExport(HttpServletRequest request,HttpServletResponse response, @RequestParam String name,@RequestParam String level,
							@RequestParam String channel,@RequestParam String isLeave,
							@RequestParam Integer depId, @RequestParam String beginDateStr,
							@RequestParam String endDateStr,@RequestParam String tieCard,
							@RequestParam String isInside, @RequestParam String recommendCode,
							@RequestParam String actUserId){

		logger.info("sysUser export excel params =[name={},level={},channel={},isLeave={},depId={},beginDateStr={}" +
				",endDateStr={},tieCard={},isInside={},recommendCode={},actUserId={}]",name,level,channel,isLeave,depId,beginDateStr,endDateStr,
				tieCard,isInside,recommendCode,actUserId);

		//保存操作记录
		addOperationLog(request,name,level,channel,isLeave,depId,beginDateStr,endDateStr,tieCard,isInside,recommendCode,actUserId);

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1  ");

		if (StringUtils.isNotEmpty(name)) {
			hqlFilter.addSql(" and (userPhone = '" + name.trim()
					+ "' or userRealName like '%" + name.trim() + "%' )");
		}

		//等级
		if (StringUtils.isNotBlank(level)) {
			hqlFilter.addSql(" and level = " + level);
		}

		//渠道
		if(StringUtils.isNotBlank(channel)){
			hqlFilter.addSql(" and channel = " + channel);
		}

		//是否离职
		if(StringUtils.isNotBlank(isLeave)){
			hqlFilter.addSql(" and onType=" +isLeave);
		}

		if(depId != null && depId != 0){
			Organization org = orgService.findById(depId);
			String orgCode = org.getCode();
			hqlFilter.addSql(" and userOrgCode like '" + orgCode + "%' ");
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Date beginDate;
		Date endDate;

		try {
			// 增添日期筛选条件
			if (StringUtils.isNotBlank(beginDateStr)) {
				beginDate = format.parse(beginDateStr);
				hqlFilter.addSql(" and registCts > " + beginDate.getTime());
			}

			if (StringUtils.isNotBlank(endDateStr)) {
				endDate = format.parse(endDateStr);

				Long endTimeLong = endDate.getTime() + 60 * 60 * 24 * 1000;

				hqlFilter.addSql(" and registCts < " + endTimeLong);
			}
		} catch (ParseException e1) {
			logger.info("sysUser export excel 日期格式转换错误");
			e1.printStackTrace();
		}

		//是否绑卡
		if(StringUtils.isNotBlank(tieCard)){
			hqlFilter.addSql(" and tieCard = " + tieCard);
		}

		//是否为理财师
		if(StringUtils.isNotBlank(isInside)){
			hqlFilter.addSql(" and isInside = " + isInside);
		}

		//推荐码
		if(StringUtils.isNotBlank(recommendCode)){
			hqlFilter.addSql(" and recommendCode = " + recommendCode);
		}

		List<SysUserExcelView> userList = sysUserExcelService.findByFilter(hqlFilter);
		List<SysUserExcelMsg> msg = sysUserContext.getSysUserExcelMsg(userList);

		LinkedHashMap<String, String> struct = new LinkedHashMap<>();
		struct.put("userPhone", "账号");
		struct.put("userRealName", "姓名");
		struct.put("channelName", "所属渠道");
		struct.put("userOrgName", "部门");
		struct.put("userPost", "职务");
		struct.put("registCts", "注册时间");
		struct.put("isInside", "是否IFA");
		struct.put("finUserRealName", "理财师姓名");
		struct.put("finPhone", "理财师电话号码");
		struct.put("onType", "离职状态");
		struct.put("scoreDesc", "测评结果");
		struct.put("scoreCts", "测评时间");
		struct.put("closeAccount", "是否已销户");
		struct.put("bindFuYou", "富友是否绑卡");
		struct.put("bindHuoCai", "火柴是否绑卡");
		struct.put("bindYingMi", "盈米是否绑卡");
		struct.put("paymentNo", "银行卡号");
		struct.put("bankName", "银行分行名称");

		ExcelService excelService = new ExcelService(msg, struct);

		String title = "系统用户";
		excelService.exportToStream(response, title);
	}

	/**
	 * 新增操作记录
	 */
	private void addOperationLog(HttpServletRequest request,String name, String level, String channel,String isLeave,
								  Integer depId, String beginDateStr, String endDateStr, String tieCard,
								  String isInside,  String recommendCode, String actUserId){
		JSONObject json = new JSONObject();
		json.put("name",name);
		json.put("level",level);
		json.put("channel",channel);
		json.put("isLeave",isLeave);
		json.put("depId",depId);
		json.put("beginDateStr",beginDateStr);
		json.put("endDateStr",endDateStr);
		json.put("tieCard",tieCard);
		json.put("isInside",isInside);
		json.put("recommendCode",recommendCode);

		OperationLogDTO log = new OperationLogDTO();
		log.setEvent(OperationEvent.USER_INFO_EXPORT);
		log.setEventRequestJson(JSON.toJSONString(json,SerializerFeature.WriteMapNullValue));
		log.setOperatorId(Long.valueOf(actUserId));
		log.setTerminalIP(IPUtil.getIpAddr(request));

		operationLogService.addLog(log);
	}
	/**
	 * 用户修改推荐码之后，如果新的推荐码是理财师，则送加息券
	 */
	private void checkSendCards(SysUser user, String recommendCode) {
		String oldRecommendCode = user.getRecommendCode();
		SysUser oldFinUser = null;
		if (StringHelper.isNotEmpty(oldRecommendCode)) {
			oldFinUser = sysUserService.getByPhoneNum(recommendCode);
		}

		SysUser newFinUser = sysUserService.getByPhoneNum(recommendCode);

		// 如果用户旧的理财师为空，新的理财师不为空，则送加息券
		if (oldFinUser == null && newFinUser != null && newFinUser.getIsInside() == 1) {
			//userCardService.sendCardToUser(user);
			couponService.sendJXQToUser(user.getId());
		}
	}

	/**
	 * 用户修改推荐码之后，如果新的推荐码是理财师，则送加息券
	 */
	private void checkSendCards(SysUser user) {
		String recommendCode = user.getRecommendCode();
		if (sysUserService.isFinUserByPhoneNum(recommendCode)) {
			//userCardService.sendCardToUser(user);
			//couponService.sendJXQToUser(user.getId());
		}
	}

	private void chgUser(SysUser user, Integer newOrgId, Integer newChannelId ){
		// 保存到log中
		LogUtil logRecord = new LogUtil();

		//logRecord.setActUserId(req.getActUserId());

		logRecord.setType(ConstantLog.LOG_TYPE_USER_BASE);

		String realName = "";

		if (StringHelper.isNotEmpty(user.getRealName())) {
			realName = user.getRealName();
		}

		logRecord.setChgDesc("系统批量更改用户的组织架构 用户名   : " + realName);
		logRecord.setRecordId(user.getId());
		logRecord.setUserId(user.getId());

		// 在日志表中保存修改之前的镜像
		String beforeImgStr = JsonUtils.toJson(sysUserService.getRespUser(user.getId()));
		logRecord.setBeforeImg(beforeImgStr);

		user.setOrgId(newOrgId);
		user.setChannel(newChannelId);

		sysUserService.update(user);

		// 在日志表中保存修改之后的镜像
		String afterImgStr = JsonUtils.toJson(sysUserService
				.getRespUser(user.getId()));
		logRecord.setAfterImg(afterImgStr);
		// 加入日志表中
		logService.add(logRecord);
	}

	private Integer getChannelId(String name ){
		Integer result = 0;
		if(name.equals("多元渠道部")){
			result =  1076;
		}else	if(name.equals("内部渠道部")){
			result = 1075;
		}else	if(name.equals("直销渠道二部")){
			result = 1026;
		}else	if(name.equals("网络渠道部")){
			result = 1017;
		}else	if(name.equals("直销渠道一部")) {
			result = 3;
		}
		return result;
	}

	/**
	 * 更新用户信息并保存销户的记录
	 * @param user
	 * @param actUserId
	 */
	private void updateAndSaveCloseAccountLog(SysUser user,Long actUserId){
		// 保存到log中
		LogUtil logRecord = new LogUtil();
		logRecord.setActUserId(actUserId);
		logRecord.setType(ConstantLog.LOG_TYPE_USER_BASE);
		String realName = "";
		if (StringHelper.isNotEmpty(user.getRealName())) {
			realName = user.getRealName();
		}
		logRecord.setChgDesc("修改用户基本信息 用户名   : " + realName);
		logRecord.setRecordId(user.getId());
		logRecord.setUserId(user.getId());

		// 在日志表中保存修改之前的镜像
		String beforeImgStr = JsonUtils.toJson(sysUserService
				.getRespUser(user.getId()));
		logRecord.setBeforeImg(beforeImgStr);

		user.setCloseAccount(ConstantUser.CLOSE_ACCOUNT);
		sysUserService.update(user);

		// 在日志表中保存修改之后的镜像
		String afterImgStr = JsonUtils.toJson(sysUserService
				.getRespUser(user.getId()));
		logRecord.setAfterImg(afterImgStr);
		// 加入日志表中
		logService.add(logRecord);
	}

}
